什麼是Attribute?
Attribute
(屬性)是C#獨有的語法特性。
可以在一個Function上面戴帽子[ 🎩 ]
提供額外的訊息和觸發特定的行為。
[SerializeField]:
[SerializeField]
private int myPrivateField;
[HideInInspector]:
[HideInInspector]
public int myPublicField;
[Range(min, max)]:
[Range(0, 100)]
public int myRangeField;
[Tooltip("Description")]:
[Tooltip("This is a tooltip")]
public int myField;
[Header("Header Title")]:
[Header("My Header")]
public int myField;
[Space(height)]:
[Space(10)]
public int myField;
[Multiline]:
[Multiline]
public string myString;
[TextArea(minLines, maxLines)]:
[TextArea(3, 10)]
public string myString;
[RequireComponent(typeof(Component))]:
[RequireComponent(typeof(Rigidbody))]
public class MyComponent : MonoBehaviour
{
// ...
}
[AddComponentMenu("Menu Name")]:
[AddComponentMenu("Custom/MyComponent")]
public class MyComponent : MonoBehaviour
{
// ...
}
[ExecuteInEditMode]:
[ExecuteInEditMode]
public class MyComponent : MonoBehaviour
{
// ...
}
[DisallowMultipleComponent]:
[DisallowMultipleComponent]
public class MyComponent : MonoBehaviour
{
// ...
}
[SelectionBase]:
[SelectionBase]
public class MyComponent : MonoBehaviour
{
// ...
}
[RuntimeInitializeOnLoadMethod]:
RuntimeInitializeLoadType.AfterSceneLoad
或 RuntimeInitializeLoadType.BeforeSceneLoad
。using UnityEngine;
public class MyClass
{
[RuntimeInitializeOnLoadMethod]
static void OnRuntimeMethodLoad()
{
Debug.Log("This runs when the game starts.");
}
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void BeforeSceneLoad()
{
Debug.Log("This runs before any scene is loaded.");
}
}
[InitializeOnLoadMethod]:
using UnityEditor;
using UnityEngine;
public class MyEditorClass
{
[InitializeOnLoadMethod]
static void OnEditorLoad()
{
Debug.Log("This runs when the editor loads.");
}
}
[MenuItem]:
using UnityEditor;
using UnityEngine;
public class MyMenuItems
{
[MenuItem("MyMenu/Do Something")]
static void DoSomething()
{
Debug.Log("Doing something...");
}
[MenuItem("MyMenu/Do Something with Shortcut %g")]
static void DoSomethingWithShortcut()
{
Debug.Log("Doing something with shortcut...");
}
}
[CustomEditor]:
創建自定義編輯器,讓你自定義Inspector的顯示效果
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(MyComponent))]
public class MyComponentEditor : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
MyComponent myComponent = (MyComponent)target;
if (GUILayout.Button("Do Something"))
{
myComponent.DoSomething();
}
}
}
[Test]:
-標記Unit Test方法。
using NUnit.Framework;
public class MyTests
{
[Test]
public void MyTest()
{
Assert.AreEqual(1, 1);
}
}
[UnityTest]:
標記一個協程測試方法。
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;
public class MyUnityTests
{
[UnityTest]
public IEnumerator MyUnityTest()
{
yield return null;
Assert.AreEqual(1, 1);
}
}
如果你有使用第三方的插件
如Odin Inspector,
裡面會提供更多的Inspector擴展Attribute可以快速使用。
下一章,
我們來研究一下怎麼製作自己的Attribute :)